// pages/orderDetail/orderDetail.js
const orderService = require('../../service/orderService.js')
const accountService = require('../../service/accountService.js');
const utils = require('../../utils/util.js');
// load promise 
require('../../utils/wx-pro.js');
var timer = null
var timers = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    showToast: false,
    toastMsg: '',
    orderDetail: '',
    createTime: '',
    shopInfo: '',
    limitTime: 60 * 60 * 1000,
    remain: '',
    remainFormat: '',
    smsCode: '',
    codeText: '获取验证码',
    showPayBox: false,
    payDelay: false,
    time: 60,
    showconfirmCodeBox: false,
    serviceNum: ''
  },

  //错误提示
  showToastFuc(msg) {
    this.setData({
      showToast: true,
      toastMsg: msg
    })
    setTimeout(() => {
      this.setData({
        showToast: false,
        toastMsg: ''
      })
    }, 2000)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.orderId)
    this.setData({
      orderId: options.orderId
    })
    this.getOrderDetail()
  },

  getFormatDate(fmt, d) {
    var now = new Date();
    if (!!d) {
      now = d;
    }

    var o = {
      "M+": now.getMonth() + 1,                 //月份
      "d+": now.getDate(),                    //日
      "h+": now.getHours(),                   //小时
      "m+": now.getMinutes(),                 //分
      "s+": now.getSeconds(),                 //秒
      "q+": Math.floor((now.getMonth() + 3) / 3), //季度
      "S": now.getMilliseconds()             //毫秒
    };

    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (now.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }

    return fmt;
  },

  secondToDate(result) {
    var h = Math.floor(result / 3600);
    var m = Math.floor((result / 60 % 60));
    var s = Math.floor((result % 60));
    if (h > 0) {
      return result = h + "小时" + m + "分钟" + s + "秒";
    } else {
      return result = m + "分钟" + s + "秒";
    }
  },

  getOrderDetail(){
    var params = {orderId: this.data.orderId}
    orderService.getOrderById(params).then(data => {
      if (data.code == 200) {
        this.setData({
          shopInfo: data.response.shop,
          orderDetail: data.response.xcxOrder,
          createTime: this.getFormatDate('yyyy-MM-dd hh:mm:ss', new Date(data.response.xcxOrder.createTime)),
          remain: this.data.limitTime - (data.timestamp - data.response.xcxOrder.createTime)
        })
        if (data.response.xcxOrder['orderStatus'] == 0) {
          this.clearTimer()
          this.setTimer()
        } else {
          this.clearTimer()
        }
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch((e) => {
        console.log(e)
      })
  },
  setTimer() {
    timer = setInterval(() => {
      if (this.data.remain > 1000) {
        this.setData({
          remain: this.data.remain - 1000,
          remainFormat: this.secondToDate(this.data.remain / 1000)
        })
      } else {
        this.getOrderDetail()
      }
    }, 1000)
  },
  clearTimer() {
    timer = clearInterval(timer)
  },
  xcxCancelOrder(){
    var _this = this
    var params = { orderId: this.data.orderId }
    orderService.xcxCancelOrder(params).then(data => {
      if (data.code == 200) {
        wx.showModal({
          title: '提示',
          content: '是否取消订单？',
          confirmText: '是',
          cancelText: '否',
          success: function (res) {
            if (res.confirm) {
              _this.getOrderDetail()
            }
          }
        })
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch((e) => {
        console.log(e)
      })
  },
  showConfirmCodeBox(){
    this.setData({
      showconfirmCodeBox: true
    })
  },
  xcxOrderConfirm() {
    var _this = this
    var params = { orderId: this.data.orderId, serviceNum: this.data.serviceNum }
    orderService.xcxOrderConfirm(params).then(data => {
      if (data.code == 200) {
        _this.setData({
          showconfirmCodeBox: false
        })
        _this.getOrderDetail()
      } else {
        this.showToastFuc(data.message)
      }
    })
    .catch((e) => {
      console.log(e)
    })
  },
  payOrder(){
    var _this = this
    console.log(_this.data.orderDetail.payType)
    if (_this.data.orderDetail.payType == 1){//微信支付
      var params = { xcxOrderId: _this.data.orderDetail.orderId, paymentType: _this.data.orderDetail.payType, payMoney: _this.data.orderDetail.orderPrice }
      orderService.xcxPay(params).then(data => {
        if (data.code == 200) {
          wx.requestPayment({
            'timeStamp': data.response.payInfo.timeStamp,
            'nonceStr': data.response.payInfo.nonceStr,
            'package': data.response.payInfo.package,
            'signType': data.response.payInfo.signType,
            'paySign': data.response.payInfo.paySign,
            'success': function (res) {
              wx.showToast({
                title: '支付成功',
                icon: 'succes',
                duration: 1000
              })
              console.log(res)
              _this.getOrderDetail()
            },
            'fail': function (res) {
              console.log(res)
            }
          })

        } else {
          _this.showToastFuc(data.message)
        }
      })
        .catch(() => {
          console.log('error')
        })
    } else if (_this.data.orderDetail.payType == 4){
      _this.setData({
        showPayBox: true
      })
    }
  },
  smsCodeChange: function (e) {
    var that = this
    that.setData({
      smsCode: e.detail.value
    })
  },
  serviceNumChange: function(e){
    var that = this
    that.setData({
      serviceNum: e.detail.value
    })
  },
  sendCode: function () {
    this.setData({
      disableButton: true
    })
    accountService.sendMyVerifyCode().then(data => {
      if (data.code == 200) {
        wx.showToast({
          title: '发送成功',
          icon: 'succes',
          duration: 1000
        })
        timers = setInterval(() => {
          if (this.data.time == 0) {
            clearInterval(timers)
            this.setData({
              time: 60,
              codeText: '发送验证码',
              disableButton: false
            })
          } else {
            this.setData({
              time: this.data.time - 1,
              codeText: '重新发送(' + this.data.time + ')'
            })
          }
        }, 1000)
      }
    })
      .catch(() => {
        console.log('error')
      })
  },
  goPay(){
    if (this.data.smsCode){
      var params = { xcxOrderId: this.data.orderDetail.orderId, paymentType: this.data.orderDetail.payType, payMoney: this.data.orderDetail.orderPrice, smsCode: this.data.smsCode }
      orderService.xcxPay(params).then(data => {
        if (data.code == 200) {
          this.getOrderDetail()
          this.setData({
            showPayBox: false
          })
        } else {
          this.showToastFuc(data.message)
        }
      })
        .catch(() => {
          console.log('error')
        })
    }else{
      this.showToastFuc("请输入验证码")
    }
  },
  cancelPay(){
    this.setData({
      showPayBox: false
    })
  },
  cancelConfirm() {
    this.setData({
      showconfirmCodeBox: false
    })
  },
  delOrder(){
    var _this = this
    var params = { orderId: this.data.orderId }
    wx.showModal({
      title: '提示',
      content: '是否删除订单？',
      confirmText: '是',
      cancelText: '否',
      success: function (res) {
        if (res.confirm) {
          orderService.delXcxOrder(params).then(data => {
            if (data.code == 200) {
              wx.navigateBack({})
            } else {
              this.showToastFuc(data.message)
            }
          })
            .catch((e) => {
              console.log(e)
            })
        }
      }
    })
  },
  goShare(){
    wx.navigateTo({
      url: '../joinTheGroup/joinTheGroup?xcxGoodsId=' + this.data.orderDetail.goodId + '&OpenCode=' + this.data.orderDetail.openCode
    })
  }
})